<template>
  <div>
    <div class="aa">
      <div>{{name}}</div>
      <button @click="addName">add name</button>
    </div>
    <div class="aa">
      <div>{{num}}</div>
      <button @click="addNum">add num</button>
    </div>
  </div>

</template>

<script>
import { reactive, ref, toRefs, watch, watchEffect } from "vue";
export default {
  name: "监控",
  // 定义模板
  components: {},
  //在创建组件之前执行
  setup(props, context) {
    const state = reactive({
      name: 0,
    });
    const num = ref(0);

    const addName = () => {
      state.name++;
    };

    const addNum = () => {
      num.value++;
    };

    //监听单个
    watch(
      () => state.name,
      (newVal, oldVal) => {
        console.log(newVal, oldVal);
        if (newVal > 5) {
          state.name = oldVal;
        }
      }
    );

    //监控2个
    watch(
      [() => state.name, num],
      ([numVal, totalVal], [oldNumVal, OldTotalVal]) => {
        console.log(numVal, oldNumVal);
        console.log(totalVal, OldTotalVal);
      }
    );

    //副作用，会立即执行  优点不需要指定监听的属性，他会自动的收集依赖
    let callTimes = 0;
    const stopEffect = watchEffect(() => {
      console.log(num.value, "watchEffect打印的");
      // setTimeout(() => {
      //   num.value++;
      // }, 1000);
      // 调用 5 次后，取消effect监听
      callTimes++;
      if (callTimes >= 5) stopEffect();
    });
    return {
      ...toRefs(state),
      num,
      addName,
      addNum,
    };
  },
};
</script>
<style scoped lang ='less'>
.aa {
  margin-bottom: 50px;
}
</style>